package com.xyz.orderservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xyz.entity.R;
import com.xyz.constants.ResultCode;
import com.xyz.utils.JwtUtil;
import com.xyz.orderservice.entity.TOrder;
import com.xyz.orderservice.service.TOrderService;
import com.xyz.exceptionhandler.BusinessException;


import io.swagger.v3.oas.annotations.media.Schema;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author zsr
 * @since 2021-06-22
 */
@Schema(description = "订单接口")
@RestController
@CrossOrigin
@RequestMapping("/orderservice/order")
public class TOrderController {

    @Autowired
    private TOrderService orderService;

    //根据课程id和用户id创建订单，返回订单id
    @Schema(description="生成订单")
    @PostMapping("createOrder/{courseId}")
    public R save(@PathVariable String courseId, HttpServletRequest request) {
        String id = JwtUtil.getMemberIdByJwtToken(request);//用户id
        id = "1";
        if (StringUtils.isEmpty(id)) throw new BusinessException(ResultCode.NOLOGIN.getCode(), "未登录");
        String orderId = orderService.saveOrder(courseId, id);
        return R.ok().data("orderId", orderId);

    }

    @Schema(description="获取订单详情")
    @GetMapping("getOrder/{orderId}")
    public R get(@PathVariable String orderId) {
        QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no", orderId);
        TOrder order = orderService.getOne(wrapper);
        return R.ok().data("item", order);
    }

    @GetMapping("isBuyCourse/{memberid}/{id}")
    public boolean isBuyCourse(@PathVariable String memberid,
                               @PathVariable String id) {
        //订单状态是1表示支付成功
        Long count = orderService.count(new QueryWrapper<TOrder>().eq("member_id", memberid).eq("course_id", id).eq("status", 1));

        return count > 0;
    }
}

